import sys
from mokocard.util.exceptionutil import printStack

class LogUtil:
    
    logFile = None
    stdoutMode = False
    
    def __init__ (self, pathLogFile, stdoutMode):
        # static variable       
        LogUtil.stdOutMode = stdoutMode
        # if standard output mode equals False write to file
        if stdoutMode == False:
            self.openLogFile(pathLogFile)

    @staticmethod
    def writeLog(message):
        # no file using standard output
        if LogUtil.stdoutMode == True or LogUtil.logFile == None:
            print(message)
        else:
            LogUtil.logFile.write(message + "\n")
            
    def openLogFile(self, pathLogFile):
        try:
            if LogUtil.logFile == None:
                LogUtil.logFile = open(pathLogFile, 'w')
        except:
            self.writeLog(printStack(sys.exc_info()))
        
    def closeLogFile(self):
        try:
            if LogUtil.logFile != None:
                self.logFile.close()
                print "log file closed"
        except:
            printStack(sys.exc_info())